import axios from "axios";
import { buildQueryString } from "../utils/helpers";
import mockDataNotifier from "../utils/mockDataNotifier";
import { getGlobalMessageApi } from "../contexts/MessageContext";
import {
  mockSamples,
  mockDevices,
  mockDeviceData,
  mockTempHumidityData,
  mockDeviceParams,
  createMockResponse,
  filterSamples,
  filterDevices,
  filterDeviceData,
  filterTempHumidityData,
  filterDeviceParams,
} from "./mockData";

// 根据环境获取API基础URL
const getApiBaseUrl = () => {
  // 开发环境使用代理，生产环境使用实际地址
  if (import.meta.env.MODE === "production") {
    return "/api/1.0.0/platform/ghy/way"; // 开发环境使用代理
  } else {
    return "/api/1.0.0/platform/ghy/way"; // 生产环境直接访问
  }
};

// 创建axios实例
const api = axios.create({
  baseURL: getApiBaseUrl(),
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    const data = response.data;

    // 检查业务逻辑错误
    if (data && typeof data.code === "number") {
      // 成功的响应码通常是 200 或 0
      if (data.code === 200 || data.code === 0) {
        return data;
      } else {
        // 业务逻辑错误
        const errorMsg = data.msg || data.message || "请求失败";
        console.error("业务逻辑错误:", data);

        // 使用message显示错误
        const messageApi = getGlobalMessageApi();
        if (messageApi) {
          messageApi.error(`请求错误 [${data.code}]: ${errorMsg}`, 4);
        } else {
          console.error(`请求错误 [${data.code}]: ${errorMsg}`);
        }

        // 创建一个业务错误对象
        const businessError = new Error(errorMsg);
        businessError.code = data.code;
        businessError.data = data;
        businessError.isBusiness = true;

        return Promise.reject(businessError);
      }
    }

    return data;
  },
  (error) => {
    console.error("API请求错误:", error);

    // 显示用户友好的错误提示
    let errorMessage = "网络请求失败";
    if (error.code === "ECONNABORTED") {
      errorMessage = "请求超时，请检查网络连接";
    } else if (error.code === "ERR_NETWORK") {
      errorMessage = "网络连接失败，请检查网络状态";
    } else if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          errorMessage = "请求参数错误";
          break;
        case 401:
          errorMessage = "未授权访问";
          break;
        case 403:
          errorMessage = "访问被拒绝";
          break;
        case 404:
          errorMessage = "请求的资源不存在";
          break;
        case 500:
          errorMessage = "服务器内部错误";
          break;
        default:
          errorMessage = `请求失败 (${status})`;
      }
    }

    // 使用message显示网络错误
    const messageApi = getGlobalMessageApi();
    if (messageApi) {
      messageApi.error(`网络错误: ${errorMessage}`, 4);
    } else {
      console.error(`网络错误: ${errorMessage}`);
    }
    return Promise.reject(error);
  }
);

// 创建带fallback的API调用函数
const apiWithFallback = async (apiCall, fallbackData, apiName = "") => {
  try {
    return await apiCall();
  } catch (error) {
    // 如果是业务逻辑错误，不使用模拟数据，直接抛出错误
    if (error.isBusiness) {
      throw error;
    }

    // 只有网络错误才使用模拟数据
    console.warn("API调用失败，使用模拟数据:", error.message);

    // 使用新的通知器显示模拟数据提示
    mockDataNotifier.notifyMockData(apiName, {
      showMessage: true,
      showDetailedInfo: true,
      duration: 4,
    });

    return await fallbackData();
  }
};

// 样地管理API
export const sampleAPI = {
  // 添加样地信息
  addGhySample: (data) => api.post("/addGhySample", data),

  // 修改样地信息
  editGhySample: (data) => api.post("/editGhySample", data),

  // 删除样地信息
  delGhySample: (ids) => api.post("/delGhySample", { ids }),

  // 获取样地列表
  getSampleList: (params) =>
    apiWithFallback(
      () => api.get(`/getSampleList${buildQueryString(params)}`),
      () => {
        // 应用搜索过滤
        const filteredSamples = filterSamples(mockSamples, params);
        return createMockResponse(filteredSamples);
      },
      "获取样地列表"
    ),
};

// 设备管理API
export const deviceAPI = {
  // 添加设备信息
  addGhyDevice: (data) => api.post("/addGhyDevice", data),

  // 修改设备信息
  editGhyDevice: (data) => api.post("/editGhyDevice", data),

  // 删除设备信息
  delGhyDevice: (ids) => api.post("/delGhyDevice", { ids }),

  // 查询设备列表
  getDeviceList: (params) =>
    apiWithFallback(
      () => api.get(`/getDeviceList${buildQueryString(params)}`),
      () => {
        // 应用搜索过滤
        const filteredDevices = filterDevices(mockDevices, params);
        return createMockResponse(filteredDevices);
      },
      "获取设备列表"
    ),
};

// 数据查询API
export const dataAPI = {
  // 查询数据列表
  getDeviceDataList: (params) =>
    apiWithFallback(
      () => api.get(`/getDeviceDataList${buildQueryString(params)}`),
      () => {
        // 应用搜索过滤
        const filteredData = filterDeviceData(mockDeviceData, params);
        return createMockResponse(filteredData);
      },
      "获取设备数据列表"
    ),

  // 查询温湿度列表
  getDeviceTmpRHList: (params) =>
    apiWithFallback(
      () => api.get(`/getDeviceTmpRHList${buildQueryString(params)}`),
      () => {
        // 应用搜索过滤
        const filteredData = filterTempHumidityData(
          mockTempHumidityData,
          params
        );
        return createMockResponse(filteredData);
      },
      "获取温湿度数据"
    ),

  // 查询设备参数信息
  getDeviceParamList: (params) =>
    apiWithFallback(
      () => api.get(`/getDeviceParamList${buildQueryString(params)}`),
      () => {
        // 应用搜索过滤
        const filteredData = filterDeviceParams(mockDeviceParams, params);
        return createMockResponse(filteredData);
      },
      "获取设备参数"
    ),

  // 添加设备数据
  setDeviceData: (data) => api.post("/setDeviceData", data),

  // 获取设备原始数据
  getGhyDeviceOriginData: (params) =>
    apiWithFallback(
      () => api.get(`/getGhyDeviceOriginData${buildQueryString(params)}`),
      () => {
        // Mock数据 - 为每种类型提供示例数据
        const allMockData = [
          // Type 1: 设备数据
          {
            id: "type1_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 1,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, -78, 29, 1, -56, 0,
              10, 14, 0, 0, 0, 9, 1, 99, 8, -4, 0, 0, 0, 0, 86, -51, 10, 13, 76,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 9, 24, -86, -86, -102,
              -50, 10, 14, 0, 0, 0, 12, 1, 101, 9, -60, 0, 0, 0, 0, 95, -2, 10,
              13, 76,
            ],
            updatedAt: 1758509745,
          },
          {
            id: "type1_2",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 1,
            uploadData: [
              -86, -120, 2, 0, 0, 0, 37, 9, 9, -86, 4, 0, -78, 29, 1, -56, 0,
              10, 14, 0, 0, 0, 10, 1, 100, 9, -4, 0, 0, 0, 0, 87, -50,
            ],
            updatedAt: 1758509750,
          },
          // Type 2: 温湿度
          {
            id: "type2_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 2,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, -64, 0, 2, -45, -67,
              -53, 104, -60, 9, -120, 19, -21, -53, -53, 104, -60, 9, -120, 19,
              -3, -39, -53, 104, -60, 9, -120, 19, 124, 43, -51, 104, -60, 9,
              -120, 19, -7, 124, -50, 104, -60, 9, -120, 19, 108, -50, -49, 104,
              -60, 9, -120, 19, 118, -69, -103,
            ],
            updatedAt: 1758509746,
          },
          // Type 3: 基本信息
          {
            id: "type3_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 3,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, 18, 0, 3, 34, 23, 1,
              -77, -12, 1, -80, -70, -48, 104, -68, 116, -61, 65, 113, 61, -28,
              66, -40, -69, -103,
            ],
            updatedAt: 1758509747,
          },
          // Type 4: 4G测量设备
          {
            id: "type4_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 4,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, 25, 0, 4, 45, 78, 32,
              78, 45, 78, 32, 78, 45, 78, 32, 78, -103,
            ],
            updatedAt: 1758509748,
          },
          // Type 5: 上报数据
          {
            id: "type5_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 5,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, 30, 0, 5, 65, 66, 67,
              68, 69, 70, 71, 72, 73, 74, -69, -103,
            ],
            updatedAt: 1758509749,
          },
          // Type 6: 固件信息
          {
            id: "type6_1",
            batch: params.batch || 250908,
            code: params.code || 4,
            type: 6,
            uploadData: [
              -86, -120, 1, 0, 0, 0, 37, 9, 8, -86, 4, 0, 45, 0, 6, 52, 54, 48,
              48, 52, 49, 54, 52, 48, 52, 50, 57, 56, 55, 53, 66, 108, 101, 71,
              119, 45, 82, 86, 53, 46, 50, 46, 53, 0, 0, 83, 74, 95, 52, 71, 95,
              77, 66, 95, 82, 49, 68, 0, 0, 0, -49, -69, -103,
            ],
            updatedAt: 1758509747,
          },
        ];

        // 如果指定了type参数，只返回对应类型的数据
        let filteredData = allMockData;
        if (params.type !== undefined) {
          filteredData = allMockData.filter(
            (item) => item.type === parseInt(params.type)
          );
        }

        return createMockResponse(filteredData, params);
      },
      "获取设备原始数据"
    ),

  // 查询最近5次数据对比
  queryGhyLast5: (params) =>
    apiWithFallback(
      () => api.get(`/queryGhyLast5${buildQueryString(params)}`),
      () => {
        // Mock数据 - 返回5个list的数据结构
        const generateMockListData = (listIndex) => {
          const baseData = [];
          const itemCount = 40 + Math.floor(Math.random() * 10); // 40-49 个数据项

          // 为不同的 list 生成不同的 code 范围，制造一些差异
          let codeRange = [];
          switch (listIndex) {
            case 1: // list1: code 1-50
              codeRange = Array.from({ length: 50 }, (_, i) => i + 1);
              break;
            case 2: // list2: code 1-50 但缺少 23, 34, 45
              codeRange = Array.from({ length: 50 }, (_, i) => i + 1).filter(
                (code) => ![23, 34, 45].includes(code)
              );
              break;
            case 3: // list3: code 1-48 但缺少 12, 25
              codeRange = Array.from({ length: 50 }, (_, i) => i + 1).filter(
                (code) => ![12, 25, 49, 50].includes(code)
              );
              break;
            case 4: // list4: code 5-54 (有额外的51-54，缺少1-4)
              codeRange = Array.from({ length: 50 }, (_, i) => i + 5);
              break;
            case 5: // list5: code 1-45 (缺少46-50)
              codeRange = Array.from({ length: 45 }, (_, i) => i + 1);
              break;
            default:
              codeRange = Array.from({ length: 50 }, (_, i) => i + 1);
          }

          // 随机选择一些 code 来生成数据
          const selectedCodes = codeRange
            .sort(() => 0.5 - Math.random())
            .slice(0, itemCount);

          for (let i = 0; i < itemCount; i++) {
            baseData.push({
              id: `${
                [
                  "7ef290cb59240869c5c49a1a8ab5f4",
                  "cc69dbe06fa1asfbee7fddc6a84e460",
                  "b83dc6fc36345b0fdcdcf6d5522e5d",
                ][Math.floor(Math.random() * 3)]
              }${i}`,
              sample: 10,
              waybatch: 250928,
              waycode: [6, 7, 8, 9, 10, 11, 12][Math.floor(Math.random() * 7)], // 随机waycode
              type: 0,
              batch: 250922,
              code: selectedCodes[i] || i + 1, // 使用选定的 code
              voltage: 359 + Math.floor(Math.random() * 20),
              mesa: 0,
              angle: 100 + Math.floor(Math.random() * 50),
              tmp: 2700 + Math.floor(Math.random() * 200),
              rssi: -61 - Math.floor(Math.random() * 10),
              seconds: 0,
              lng: 95.1 + Math.random() * 0.1,
              lat: 95.1 + Math.random() * 0.1,
              updatedAt: 1759138376 + i * 1000,
              delFlag: false,
            });
          }
          return baseData;
        };

        const mockData = {
          list1: generateMockListData(1),
          list2: generateMockListData(2),
          list3: generateMockListData(3),
          list4: generateMockListData(4),
          list5: generateMockListData(5),
        };

        // 添加每个list的size属性
        Object.keys(mockData).forEach((listKey) => {
          mockData[`${listKey.replace("list", "size")}`] =
            mockData[listKey].length;
        });

        return {
          code: 0,
          msg: "system.success",
          data: mockData,
        };
      },
      "查询最近5次数据"
    ),
};

// CMD指令管理API
export const cmdAPI = {
  // 查询指令列表
  queryCmds: (params) =>
    apiWithFallback(
      () => api.get(`/queryCmds${buildQueryString(params)}`),
      () => {
        // Mock数据 - 指令列表（与实际API响应格式一致）
        const mockCmds = [
          {
            id: "810702f48a3a494184dcddb002635cf5",
            batch: params.batch || 250928,
            code: params.code || 6,
            uploadData: [18, 49, 35], // 对应16进制 12 31 23
            updatedAt: 1761201646,
          },
          {
            id: "920803a59b4b595295eddec113746dg6",
            batch: params.batch || 250928,
            code: params.code || 6,
            uploadData: [26, 43, 60, 77], // 对应16进制 1a 2b 3c 4d
            updatedAt: 1761201650,
          },
        ];
        return {
          code: 0,
          msg: "操作成功",
          data: mockCmds,
        };
      },
      "查询指令列表"
    ),

  // 删除指令
  deleteCmds: (id) => api.post("/deleteCmds", { id }),

  // 发送指令
  sendCmd: (data) => api.post("/sendCmd", data),
};

// FOTA 文件管理 API
export const fotaAPI = {
  // 查询当前最新版本文件（按版本查询）
  getfota: (params) =>
    apiWithFallback(
      () => api.get(`/getfotaList${buildQueryString(params)}`),
      () => {
        // Mock：返回一个示例FOTA记录
        const mock = {
          id: "mock_fota_1",
          version: params?.version ?? 1,
          bak: "示例备注",
          downfile: [
            { url: "http://www.example.com/app.py", file_name: "/usr/app.py" },
            {
              url: "http://www.example.com/test.txt",
              file_name: "/usr/text.txt",
            },
          ],
          createdAt: Math.floor(Date.now() / 1000),
        };
        return {
          code: 0,
          msg: "操作成功",
          data: mock,
        };
      },
      "查询FOTA文件"
    ),

  // 添加FOTA文件（bak、version、downfile(JSON数组或字符串)）
  addfota: (data) =>
    apiWithFallback(
      () => api.post(`/addfota`, data),
      () => {
        return {
          code: 0,
          msg: "添加成功(模拟)",
          data: {
            id: `mock_${Date.now()}`,
            ...data,
            createdAt: Math.floor(Date.now() / 1000),
          },
        };
      },
      "添加FOTA文件"
    ),

  // 删除FOTA文件（通过id）
  delfota: (id) =>
    apiWithFallback(
      () => api.get(`/delfota${buildQueryString({ id })}`),
      () => ({
        code: 0,
        msg: "删除成功(模拟)",
        data: null,
      }),
      "删除FOTA文件"
    ),
};

export default api;
